package com.usian.third.utils;

import com.alibaba.fastjson.JSON;
import com.usian.pojo.UserCheckDto;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 三要素
 * **/
public class VerifyRealName {

    /***
     *idcardx 身份证号
     * name 姓名
     *mobile 手机号
     *     return
     *     1:一致
     *     2:不一致
     *     3:无记录
     *     4:异常
     * */
    public Map checkUser(String idcard, String name, String mobile)throws IOException {
        String url = "https://transfer3.market.alicloudapi.com/mobile_three/transfer";
        String appCode = "140701f652514363bdd4907e9149ff07";
        Map<String, String> params = new HashMap<>();
        params.put("idcard",idcard);
        params.put("name",name);
        params.put("mobile",mobile);

        String result = postForm(appCode, url, params);
        UserCheckDto userCheckDto= JSON.parseObject(result,UserCheckDto.class);
        Map map=new HashMap();
        if (userCheckDto.getCode()!=0){
            /* return userCheckDto.getMsg();*/
            map.put("code",userCheckDto.getCode());
            map.put("msg",userCheckDto.getMsg());
            return map;
        }else{
//            String res=userCheckDto.getData().getResult();
//            map.put(userCheckDto.getCode(),res);
            map.put("code",userCheckDto.getCode());
            map.put("msg",userCheckDto.getMsg());
            return map;
        }
//            System.out.println("匹配结果code为："+userCheckDto.getData().getResult());
//            System.out.println("匹配结果描述："+userCheckDto.getData().getDesc());
    }

    /**
     * 用到的HTTP工具包：okhttp 3.13.1
     * <dependency>
     * <groupId>com.squareup.okhttp3</groupId>
     * <artifactId>okhttp</artifactId>
     * <version>3.13.1</version>
     * </dependency>
     */
    public static String postForm(String appCode, String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
//            System.out.println("返回状态码" + response.code() + ",message:" + response.message());
        String result = response.body().string();
        return result;
    }
}
